/*
 * Developer : Jack Matthews
 * Email: developer@droidprofessor.com
 * 
 * Copyright (C) 2010 http://droidprofessor.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.droidprofessor.android.library.phonelicenses;

 
import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.droidprofessor.android.library.phonelicenses.R;
import com.droidprofessor.android.licensegenerator.client.AndroidClientLicenseImpl;
import com.droidprofessor.licensegenerator.lib.Feature;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;


/**
 * 
 * @author Jack Matthews
 * @copyright droidprofessor.com
 * 
 * 
 */
 public class BackgroundHelperService extends IntentService {
	private static final String TAG = "BackgroundHelperService";

	//Actions
	public static final String ACTION_DOWNLOAD_LICENSE = "com.droidprofessor.android.library.digitalsignatures.ACTION_DOWNLOAD_LICENSE";

	//Notifications IDs
	private static final int NOTIFICTION_LICENSE_DOWNLOADED_ID = 0;
	private static final int NOTIFICTION_ERROR_ID = 1;
		
	
	//Services
	private NotificationManager notificationManager;
	private static Notification notifyError;
	private static Notification notifyLicenseDownload;
	
	public BackgroundHelperService() {
		super("BackgroundHelperService");
		Log.d(TAG, "Background Helper Service Created");
	}
	
	
	@Override
	protected void onHandleIntent(Intent intent) {
		//Get hold of the notification manager
		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		//notifications
		if(BackgroundHelperService.notifyError == null)
			notifyError = new Notification(
					android.R.drawable.stat_notify_error, 
					getString(R.string.com_phonelicenses_alert_notification), 
					System.currentTimeMillis()
					);
		
		if(BackgroundHelperService.notifyLicenseDownload == null)
			notifyLicenseDownload = new Notification(
					R.drawable.com_phonelicenses_license_notification, 
					getString(R.string.com_phonelicenses_license_downloaded), 
					System.currentTimeMillis()
					);
		
		if(intent == null) { //Someone was getting an error here, not sure why
			Log.e(TAG, "No Intent supplied");
			return;
		}
		
		if(intent.getAction() == null) {
			Log.e(TAG, "No Action supplied");
			return;
		}
		
		//Chose the Action to perform
		if(intent.getAction().equals(ACTION_DOWNLOAD_LICENSE))
			downloadLicense();
		else
			Log.e(TAG, "Unsupported Action supplied");
	}

	
	
	
	/**
	 * Attempt to download the license from the server
	 */
	void downloadLicense() {
		
		Context cnx = getApplicationContext();
		

		//Login details
		List<NameValuePair> post = new ArrayList<NameValuePair>(); 
		post.add(new BasicNameValuePair("username", PreferencesHelper.getUsername(cnx)));
		post.add(new BasicNameValuePair("passwd", PreferencesHelper.getPassword(cnx)));
		post.add(new BasicNameValuePair("application_id", AndroidClientLicenseImpl.getInstance().getApplicationId() ));
		post.add(new BasicNameValuePair("auth_key", AndroidClientLicenseImpl.getInstance().getAuthKey() )); 
		post.add(new BasicNameValuePair("phone_os", "Android ("+android.os.Build.VERSION.RELEASE+")" ));
		post.add(new BasicNameValuePair("phone_model", android.os.Build.MODEL  ));

		//Add Features
		for(Feature f : Feature.getEnabledFeatures()) {
			post.add(new BasicNameValuePair(f.getKey(), f.getValue()));
		}
		
		//Joomla requirements
		List<NameValuePair> get = new ArrayList<NameValuePair>();
		get.add(new BasicNameValuePair("option", "com_phonelicenses" ));    
		get.add(new BasicNameValuePair("view", "user" ));    
		get.add(new BasicNameValuePair("controller", "user" ));    
		get.add(new BasicNameValuePair("task", "get_license" ));    
		get.add(new BasicNameValuePair("format", "xml" )); 
		
		HttpResponse response = HttpUrlRequest.sendRequestForImmediateResponse(
				AndroidClientLicenseImpl.getInstance().getScheme(),
				AndroidClientLicenseImpl.getInstance().getHost(),
				AndroidClientLicenseImpl.getInstance().getPort(), 
				AndroidClientLicenseImpl.getInstance().getPath(),
				get, 
				post
				);
		
		
		
		//Common code required by all HTTP responses
		if(response==null) {
			notifyError(getString(R.string.com_phonelicenses_communication_error));
			Log.w(TAG, getString(R.string.com_phonelicenses_communication_error));
			return;
		}
		
		HttpEntity entity = response.getEntity();
		BufferedInputStream bis;
		
		try {
			if(entity != null) {
				InputStream in = entity.getContent();
				bis = new BufferedInputStream(in);
				Utils.logInpuStream(bis);
			}
			else {
				Log.e(TAG, getString(R.string.com_phonelicenses_no_internet) );
				return;
			}
		} catch (IllegalStateException e) {
			notifyError("IllegalStateException");
			Log.e(TAG, "IllegalStateException", e);
			return;
		} catch (IOException e) {
			notifyError("IOException");
			Log.e(TAG, "IOException", e);
			return;
		}

		
		XmlResponse<String> xmlResponse = XmlParser.parseXmlLicense(bis);

		if(xmlResponse.isError()) {
			//notify the user
			notifyError(xmlResponse.getMessage());
			Log.e(TAG, xmlResponse.toString() );	
		} else { //ALL WAS OK
			Log.d(TAG, xmlResponse.toString());
			
			String license = xmlResponse.getObject().trim(); 
			
			//Write the file
			FileOutputStream fos;
			try {
				fos = cnx.openFileOutput(AndroidClientLicenseImpl.getInstance().getLicenseFile(this).getName(), Context.MODE_PRIVATE);
				fos.write(license.getBytes());
			} catch (FileNotFoundException e) {
				Log.e(TAG, "Writing License failed", e);
				notifyError("Writing License failed: FileNotFoundException");
				return;
			} catch (IOException e) {
				Log.e(TAG, "Writing License failed", e);
				notifyError("Writing License failed: IOException");
				return;
			}
			
			
			
			//load the new license details into memory
			AndroidClientLicenseImpl.getInstance().reload(this);
			
			//notify the user
			notifyLicenseDownload.when = System.currentTimeMillis();
			PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(), 0);
			notifyLicenseDownload.number++;
			//notification.defaults |= Notification.DEFAULT_SOUND;
			notifyLicenseDownload.defaults |= Notification.DEFAULT_VIBRATE;
			notifyLicenseDownload.defaults |= Notification.DEFAULT_LIGHTS;
			notifyLicenseDownload.flags |= Notification.FLAG_AUTO_CANCEL;
			notifyLicenseDownload.setLatestEventInfo(
					getApplicationContext(), ""+" x ("+ notifyLicenseDownload.number +")", 
					getString(R.string.com_phonelicenses_license_downloaded), 
					pi
					);
			
			notificationManager.notify(NOTIFICTION_LICENSE_DOWNLOADED_ID, notifyLicenseDownload);
		}
		
		
		Log.d(TAG, "Finished Processing License Download");
		
		
		
//		//process the response
//		if(response==null) {
//			Log.w(TAG, getString(R.string.com_phonelicenses_communication_error));
//			return;
//		}
//
//		HttpEntity entity = response.getEntity();
//		try {
//			if(entity != null) {
//				
//				InputStream in = entity.getContent();
//				BufferedInputStream bis = new BufferedInputStream(in);
//				Utils.logInpuStream(bis);
//	
//				String license = XmlHelper.parseXmlResponse(cnx, bis).trim(); 
//				
//				//Write the file
//				FileOutputStream fos = cnx.openFileOutput(AndroidClientLicenseImpl.getInstance().getLicenseFile(this).getName(), Context.MODE_PRIVATE);
//				fos.write(license.getBytes()); 
//				
//				//load the new license details into memory
//				AndroidClientLicenseImpl.getInstance().reload(this);
//				
//				//notify the user
//				notifyLicenseDownload.when = System.currentTimeMillis();
//				PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(), 0);
//				notifyLicenseDownload.number++;
//				//notification.defaults |= Notification.DEFAULT_SOUND;
//				notifyLicenseDownload.defaults |= Notification.DEFAULT_VIBRATE;
//				notifyLicenseDownload.defaults |= Notification.DEFAULT_LIGHTS;
//				notifyLicenseDownload.flags |= Notification.FLAG_AUTO_CANCEL;
//				notifyLicenseDownload.setLatestEventInfo(
//						getApplicationContext(), ""+" x ("+ notifyLicenseDownload.number +")", 
//						getString(R.string.com_phonelicenses_license_downloaded), 
//						pi
//						);
//				
//				notificationManager.notify(NOTIFICTION_LICENSE_DOWNLOADED_ID, notifyLicenseDownload);
//
//			}
//		} catch (IllegalStateException e) {
//			if(Logging.ERROR) e.printStackTrace();
//			notifyError(getString(R.string.com_phonelicenses_server_request_failed_unexpectedly));
//		} catch (XmlPullParserException e) {
//			if(Logging.ERROR) e.printStackTrace();
//			notifyError(getString(R.string.com_phonelicenses_xml_error));
//		} catch (IOException e) {
//			if(Logging.ERROR) e.printStackTrace();
//			notifyError(getString(R.string.com_phonelicenses_server_request_failed_unexpectedly));
//		} catch (InvalidXmlDocumentException e) {
//			String message = e.getMessage()==null?cnx.getString( R.string.com_phonelicenses_communication_error):e.getMessage();
//			Log.d(TAG, message);
//			notifyError(message);
//		} catch (XmlServerErrorException e) {
//			String message = e.getMessage()==null?cnx.getString( R.string.com_phonelicenses_communication_error):e.getMessage();
//			Log.d(TAG, message);
//			notifyError(message);
//		}
//		
//		Log.d(TAG, "Finished Processing License Download");
	}
	
	
	

	private void notifyError(String message) {

		notifyError.when = System.currentTimeMillis();
		PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(), 0);
		notifyError.number++;
		//notification.defaults |= Notification.DEFAULT_SOUND;
		notifyError.defaults |= Notification.DEFAULT_VIBRATE;
		notifyError.defaults |= Notification.DEFAULT_LIGHTS;
		notifyError.flags |= Notification.FLAG_AUTO_CANCEL;
		notifyError.setLatestEventInfo(
				getApplicationContext(), getString(R.string.com_phonelicenses_alert_notification)+" x ("+notifyError.number+")", 
				message, 
				pi
				);
		
		notificationManager.notify(NOTIFICTION_ERROR_ID, notifyError);
		
	}


	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "Background Helper Service Destroyed");
	}
	
	
	

}
